package com.example.csmall.product.repository.impl;

import com.example.csmall.product.pojo.vo.CategoryListItemVO;
import com.example.csmall.product.repository.CategoryCacheRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Repository
@Slf4j
public class CategoryCacheRepositoryImpl implements CategoryCacheRepository {

    @Autowired
    RedisTemplate<String, Serializable> redisTemplate;

    private String key = "categoryList";

    @Override
    public void save(List<CategoryListItemVO> categoryListItemVO) {
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();;
        for (CategoryListItemVO listItemVO : categoryListItemVO) {
            ops.rightPush(key,listItemVO);
        }
        log.debug("CategoryCache中的save方法被执行:");
    }

    @Override
    public boolean delete() {
        Boolean delete = redisTemplate.delete(key);
        return delete;
    }

    @Override
    public  List<CategoryListItemVO> list() {
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();;
        List<Serializable> range = ops.range(key, 0, -1);
        List<CategoryListItemVO> listItemVOS = new ArrayList<>();
        for (Serializable serializable : range) {
            listItemVOS.add((CategoryListItemVO) serializable);
        }
        log.debug("CategoryCache中的list方法被执行");
        return listItemVOS;
    }

}
